import { Controller, Get, Post, Body, Inject, Query, Req, Headers } from '@nestjs/common';
import { UploadService } from './upload.service';
import { UploadDto } from './dto/upload.dto';
import { RequireLogin, UserInfo } from 'src/custom.decorator';
import { ConfigService } from '@nestjs/config';
import { Request } from 'express';
@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Inject(ConfigService)
  private configService: ConfigService

  // minio signed
  @Get()
  @RequireLogin()
  async presignedUrl(@Query('name') name: string, @Query('type') type: number, @Headers() headers:any) {
    console.log(headers.host, 'req')
    const env = this.configService.get('environment')
    
    // 生产环境会返回localhost:9000，要改为域名+代理
    const uploadUrl = await this.uploadService.preSign({name, type})
    const endPoint = this.configService.get('minio_endPoint')
    if(env === 'prod') {
      return uploadUrl.replace('localhost:9000', endPoint)
    } else {
      return uploadUrl
    }
  }

  @Post('uploadFile')
  @RequireLogin()
  async uploadFile(@Body() uploadDto: UploadDto, @UserInfo('userId') userId: number, @Req() req:Request) {
    return await this.uploadService.uploadFile(uploadDto, userId, req)
  }

  @Get('list')
  async getUploadList (@Query('pageNo') pageNo: number, @Query('pageSize') pageSize:number, @Query('type') type: number) {
    return await this.uploadService.getUploadList({pageNo, pageSize, type})
  }

  // oss signed
  @Get('oss-signed')
  async getOssSigned() {
    return await this.uploadService.ossSigned()
  }

  @Post('deleteImageByUrl')
  async deleteImage(@Body('url') url: string) {
    return await this.uploadService.deleteImageByUrl(url)
  }
  @Post('multiDelete')
  async multiDelete(@Body('urls') urls: string) {
    return await this.uploadService.multiDelete(urls)
  }
}
